﻿using System.Windows;
using YY.Admin.Core.Session;
using YY.Admin.FluentValidation;
using YY.Admin.Services;
using YY.Admin.Services.Service.Auth;
using YY.Admin.Views;

namespace YY.Admin.ViewModels
{
    // ViewModels/LoginViewModel.cs
    public class LoginWindowViewModel : BaseViewModel 
    {
        private readonly ISysAuthService _authService;
        public LoginInput LoginInput { get; set; }
        private string _loginMessage = string.Empty;
        public DelegateCommand LoginCommand { get; }
        public LoginInputValidator LoginInputValidator { get; private set; }
        public LoginWindowViewModel(
            ISysAuthService authService,
            IContainerExtension _container,
            IRegionManager regionManager
            ) : base(_container, regionManager)
        {
            _authService = authService;
            Title = "系统登录";

            LoginInput = new LoginInput()
            {
                Username = "admin",
                Password = "123456"
            };

            LoginInputValidator = new LoginInputValidator();

            LoginCommand = new DelegateCommand(async () => await LoginAsync(), CanLogin)
                //.ObservesProperty(() => LoginInput.Username)
                //.ObservesProperty(() => LoginInput.Password)
                .ObservesProperty(() => IsLoading);
            //_userEvent = subscriber;
            //_userEvent.SubscribeEvents();
        }

        public string LoginMessage
        {
            get => _loginMessage;
            set => SetProperty(ref _loginMessage, value);
        }

        public string LoginButtonText => IsLoading ? "登录中..." : "登录";

        protected override void OnIsLoadingChanged()
        {
            base.OnIsLoadingChanged();
            // 当 IsLoading 变化时，触发 LoginButtonText 的通知
            RaisePropertyChanged(nameof(LoginButtonText));
        }

        private bool CanLogin()
        {
            //return !string.IsNullOrWhiteSpace(LoginInput.Username) &&
            //       !string.IsNullOrWhiteSpace(LoginInput.Password) &&
            //       !IsLoading;
            return !IsLoading;
        }

        private async Task LoginAsync()
        {
            IsLoading = true;
            //LoginMessage = string.Empty;

            try
            {
                var response = await _authService.LoginAsync(LoginInput);

                if (response.Success)
                {
                    //设置会话
                    AppSession.CurrentUser = response.User;
                    // 设置用户上下文
                    SetUserContext(response.User!, response.Token);
                    // 启动定时器
                    StartTokenCheckTimer();
                    // 登录成功，打开主窗口
                    var container = ContainerLocator.Current;
                    var mainWindow = container.Resolve<MainWindow>();
                    Application.Current.MainWindow?.Hide();
                    Application.Current.MainWindow = mainWindow;
                    //把窗口和RegionManager 绑定一下即可
                    SetRegionManager(mainWindow);
                    mainWindow.Show();

                    // 不等待异步更新用户登录信息，不阻塞主窗口打开
                    _ = _authService.UpdateUserLoginInfoAsync(response.User!);
                }
                else
                {
                    LoginMessage = response.Message;
                }
            }
            catch (Exception ex)
            {
                LoginMessage = $"登录出错：{ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }
    }
}